package cn.xiaomagege.platform.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import cn.xiaomagege.platform.module.sys.entity.SysMenu;
import cn.xiaomagege.platform.module.sys.service.SysMenuService;
import cn.xiaomagege.platform.vo.Breadcrumb;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
public class BreadcrumbUtil {
    
    @Autowired
    private SysMenuService sysMenuService;
    
    public List<Breadcrumb> getBreadcrumbPath(String menuUrl) {
        List<Breadcrumb> breadcrumbs = new ArrayList<>();
        SysMenu sysMenu = sysMenuService.getMenuByUrl(menuUrl);
        
        if("-1".equals(sysMenu.getParentId())) {
            Breadcrumb bd = new Breadcrumb();
            bd.setName(sysMenu.getName());
            bd.setOrder(10);
            bd.setIsleaf("Y");
            breadcrumbs.add(bd);
            
            Breadcrumb bd2 = new Breadcrumb();
            bd2.setName("系统模块");
            bd2.setOrder(0);
            bd2.setIsleaf("N");
            breadcrumbs.add(bd2);
        } else {
            Breadcrumb bd = new Breadcrumb();
            bd.setName(sysMenu.getName());
            bd.setOrder(10);
            bd.setUrl(sysMenu.getUrl());
            bd.setIsleaf("Y");
            breadcrumbs.add(bd);
            
            List<Breadcrumb> parentBreadcrumb = getParentBreadcrumb(sysMenu.getParentId(), 9);
            breadcrumbs.addAll(parentBreadcrumb);
            
            Breadcrumb bd2 = new Breadcrumb();
            bd2.setName("系统模块");
            bd2.setOrder(0);
            bd2.setIsleaf("N");
            breadcrumbs.add(bd2);
        }
        
        Collections.reverse(breadcrumbs);
        return breadcrumbs;
    }
    
    public List<Breadcrumb> getParentBreadcrumb(String parentId, int index) {
        List<Breadcrumb> breadcrumbs = new ArrayList<>();
        SysMenu sysMenu = sysMenuService.getMenuByMenuId(parentId);
        
        if("-1".equals(sysMenu.getParentId())) {
            Breadcrumb bd = new Breadcrumb();
            bd.setName(sysMenu.getName());
            bd.setOrder(index);
            bd.setIsleaf("N");
            breadcrumbs.add(bd);
        } else {
            Breadcrumb bd = new Breadcrumb();
            bd.setName(sysMenu.getName());
            bd.setOrder(index);
            bd.setUrl(sysMenu.getUrl());
            bd.setIsleaf("N");
            breadcrumbs.add(bd);
            
            List<Breadcrumb> parentBreadcrumb = getParentBreadcrumb(sysMenu.getParentId(), index - 1);
            breadcrumbs.addAll(parentBreadcrumb);
        }
        
        return breadcrumbs;
    }
}